<template>
  <div class="body-register" ref="bgContainer">
    <div class="wrapper">
      <div class="front">
        <div class="title"><b>花智用户注册</b></div>
        <el-form :model="user" :rules="rules" ref="userForm">
          <div class="form-content">
            <el-form-item prop="username">
              <el-input 
                placeholder="请取用户名" 
                v-model="user.username"
                prefix-icon="el-icon-user"
              />
            </el-form-item>
            
            <el-form-item prop="password">
              <el-input
                placeholder="请输入密码"
                v-model="user.password"
                prefix-icon="el-icon-lock"
                show-password
                @focus="showPasswordMeter = true"
              />
              <PasswordStrengthMeter 
                v-if="showPasswordMeter" 
                :password="user.password"
              />
            </el-form-item>
            
            <el-form-item prop="confirmPassword">
              <el-input
                placeholder="请确认密码"
                v-model="user.confirmPassword"
                prefix-icon="el-icon-lock"
                show-password
              />
            </el-form-item>
            
            <el-form-item prop="mail">
              <el-input
                placeholder="请输入邮箱"
                v-model="user.mail"
                prefix-icon="el-icon-message"
              />
            </el-form-item>
            
            <el-form-item prop="realName">
              <el-input
                placeholder="请输入真实姓名"
                v-model="user.realName"
                prefix-icon="el-icon-user"
              />
            </el-form-item>
            
            <el-form-item prop="phone">
              <el-input
                placeholder="请输入联系方式"
                v-model="user.phone"
                prefix-icon="el-icon-phone"
              />
            </el-form-item>
            
            <el-form-item v-if="showCaptcha" prop="captcha">
              <el-input
                placeholder="请输入验证码"
                v-model="user.captcha"
              />
              <img :src="captchaImage" @click="refreshCaptcha" class="captcha-img"/>
            </el-form-item>
            
            <div class="actions">
              <el-button 
                type="primary" 
                @click="register" 
                :loading="loading"
              >
                注册
              </el-button>
              <el-button 
                type="warning" 
                @click="$router.push('/login')"
              >
                返回登录
              </el-button>
            </div>
          </div>
        </el-form>
      </div>
    </div>
    
    <div v-if="bgLoading" class="loading-indicator">
      背景加载中...
    </div>
  </div>
</template>

<script>
import { defineAsyncComponent, ref, getCurrentInstance } from 'vue'
import { useRouter } from 'vue-router'
import axios from 'axios'

// 配置后端接口基础URL
const userService = axios.create({
  baseURL: '/api/userservice',
  headers: {
    'Content-Type': 'application/json' // 明确指定JSON格式
  }
})

// 响应拦截器（统一错误处理）
axios.interceptors.response.use(
  (response) => response,
  (error) => {
    const msg = error.response?.data?.msg || '请求失败，请重试'
    error.message = msg // 统一错误信息格式
    return Promise.reject(error)
  }
)

// 动态加载密码强度组件
const PasswordStrengthMeter = defineAsyncComponent({
  loader: () => import('@/components/PasswordStrengthMeter.vue'),
  loadingComponent: {
    template: '<div style="margin-top:8px;font-size:12px;">加载密码强度检测器...</div>'
  },
  delay: 200,
  timeout: 3000
})

export default {
  name: "Register",
  components: { PasswordStrengthMeter },
  setup() {
    const router = useRouter()
    const { proxy } = getCurrentInstance() 
    const userForm = ref(null)
    const bgContainer = ref(null)
    
    // ====================== 表单数据 ======================
    const user = ref({
      username: '', // 改为username（与后端一致）
      password: '',
      confirmPassword: '',
      phone: '',
      mail: '',
      realName: '',
      captcha: '' // 验证码参数
    })

    // ====================== 验证码相关 ======================
    const showCaptcha = ref(false) // 是否显示验证码
    const captchaImage = ref('') // 验证码图片地址（前端模拟）
    const mockCaptcha = ref('1234') // 模拟验证码（固定值）

    // 生成/刷新验证码（前端模拟）
    const refreshCaptcha = () => {
      mockCaptcha.value = Math.random().toString().slice(2, 6) // 生成4位随机数
      captchaImage.value = `data:image/svg+xml;base64,${btoa(`<svg width="100" height="30"><text x="10" y="20">${mockCaptcha.value}</text></svg>`)}`
    }

    // ====================== 注册逻辑 ======================
    const register = async () => {
      try {
        loading.value = true
        await userForm.value.validate() // 等待表单验证完成

        // ================= 数据封装 =================
        // 按后端UserRegisterReqDTO参数名封装（username、password、mail、realName phone、captcha）
        const registerData = {
          username: user.value.username,
          password: user.value.password,
          mail: user.value.mail,
          realName: user.value.realName,
          phone: user.value.phone
        }

        // ================= 发送请求 =================
        const response =  await userService.post('/api/userservice/user/register', registerData)
        
        if (response.data.success) {
          proxy.$message.success('注册成功，请登录')
          router.push('/login')
        } else {
          // 失败时处理：累计尝试次数，达到3次显示验证码
          registerAttempts.value++
          if (registerAttempts.value >= 3) {
            showCaptcha.value = true
            refreshCaptcha() // 刷新验证码
          }
          this.$message.error(response.data.msg)
        }
      } catch (error) {
        console.error('注册失败:', error)
        if (error.response?.status === 429) {
          showCaptcha.value = true // 强制显示验证码
          refreshCaptcha()
        }
        proxy.$message.error(error.message)
      } finally {
        loading.value = false
      }
    }

    // ====================== 其他配置 ======================
    const loading = ref(false) // 注册按钮加载状态
    const registerAttempts = ref(0) // 注册尝试次数
    const showPasswordMeter = ref(false) // 密码强度显示状态

    // 表单验证规则（字段名改为username）
    const rules = {
      username: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { min: 2, max: 20, message: '长度在2到20个字符', trigger: 'blur' }
      ],
      password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 6, max: 20, message: '密码长度至少6个字符', trigger: 'blur' }
      ],
      confirmPassword: [
        { required: true, message: '请确认密码', trigger: 'blur' },
        { validator: validatePassword, trigger: 'blur' }
      ],
      phone: [
        { required: true, message: '请输入手机号', trigger: 'blur' },
        { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'blur' } // 优化手机号正则
      ],
      mail: [
        { required: true, message: '请输入邮箱', trigger: 'blur' },
        { type: 'mail', message: '邮箱格式不正确', trigger: 'blur' }
      ]
      // 验证码字段不在rules中校验，由前端逻辑控制
    }

    // 密码一致性验证
    function validatePassword(rule, value, callback) {
      if (value !== user.value.password) {
        callback(new Error('两次输入的密码不一致'))
      } else {
        callback()
      }
    }

    return {
      userForm,
      bgContainer,
      user,
      rules,
      showPasswordMeter,
      showCaptcha,
      captchaImage,
      loading,
      registerAttempts,
      refreshCaptcha,
      register,
      mockCaptcha // 前端模拟时可用于调试
    }
  },
  data() {
    return {
      bgLoaded: false,
      bgLoading: false,
      bgError: false
    }
  },
  mounted() {
    this.setupLazyLoad()
   // this.fetchCsrfToken() // 调用获取CSRF Token方法
  },
  methods: {
    // 获取CSRF Token（新增）
    // async fetchCsrfToken() {
    //   try {
    //     const response = await axios.get('/api/csrf-token')
    //     setCsrfToken(response.data.token)
    //   } catch (error) {
    //     console.error('获取CSRF令牌失败:', error)
    //   }
    // },

    // 背景图懒加载（保留原逻辑）
    setupLazyLoad() {
      if (!window.IntersectionObserver) {
        this.loadBackground()
        return
      }
      
      const observer = new IntersectionObserver((entries) => {
        entries.forEach(entry => {
          if (entry.isIntersecting && !this.bgLoaded) {
            this.loadBackground()
            observer.unobserve(entry.target)
          }
        })
      }, { rootMargin: '200px' })

      this.$nextTick(() => {
        if (this.$refs.bgContainer) {
          observer.observe(this.$refs.bgContainer)
        }
      })
    },

    loadBackground() {
      this.bgLoading = true;
      try {
        const imgUrl = new URL('@/assets/images/background.jpg', import.meta.url).href;
        this.$refs.bgContainer.style.backgroundImage = `url(${imgUrl})`;
        this.bgLoaded = true;
      } catch (e) {
        console.error('加载背景图失败:', e);
        this.bgError = true;
        this.$refs.bgContainer.style.backgroundColor = '#f0f2f5';
      } finally {
        this.bgLoading = false;
      }
    }
  }
}
</script>


<style scoped>
.body-register {
  background-color: #f0f2f5;
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
  height: 100vh;
  width: 100%;
  transition: background-image 0.5s ease;
}

.wrapper {
  height: 100vh;
  overflow: hidden;
  display: flex;
  justify-content: center;
  align-items: center;
}

.front {
  background-color: rgba(255, 255, 255, 0.7);
  width: 350px;
  padding: 30px;
  border-radius: 10px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.title {
  margin: 20px 0;
  text-align: center;
  font-size: 20px;
  font-weight: bold;
}

.form-content {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.actions {
  margin: 30px 0;
  text-align: center;
}

.captcha-img {
  margin-top: 10px;
  height: 40px;
  cursor: pointer;
}

.loading-indicator {
  position: fixed;
  bottom: 20px;
  right: 20px;
  background: rgba(0,0,0,0.7);
  color: white;
  padding: 5px 10px;
  border-radius: 4px;
  font-size: 12px;
}

/* 响应式调整 */
@media (max-width: 480px) {
  .front {
    width: 90%;
    padding: 20px;
  }
}
</style>
